import os
import sys
import net

class RawChatServerHandler(net.TCPServer):
    defaultPort = 6317
    def __init__(self,port=defaultPort):
        net.TCPServer.__init__(self)
        self.chat = []
        self.connect('localhost',port)
        #self.connect('99.110.58.77',port)
    def connect_func(self,sock,host,port):
        print "RawChatServer successfully connected to %s on port %s!" % (host,port)
    def client_connect_func(self,sock,host,port,address):
        print "A client, (ip: %s, code: %s) connected on port %s!" % (address[0],address[1],port)
    def client_disconnect_func(self,sock,host,port,address):
        print "A client, (ip: %s, code: %s) disconnected from port %s!" % (address[0],address[1],port)
    def add_message(self,message):
        self.chat.append(message)
        if len(self.chat) >= 60:
            self.chat = self.chat[1:]
    def handle_data(self,data):
        if data[1] == "add message":
            self.add_message(data[2])
        elif data[1] == "add self":
            self.add_message("[SERVER:] "+data[2]+" has joined.")
        elif data[1] == "quit self":
            self.add_message("[SERVER:] "+data[2]+" has left.")
        self.send_data(self.chat)

def main():
    server = RawChatServerHandler()
    server.serve_forever()
    server.quit()

if __name__ == '__main__':
    main()
